package com.music.common.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.appengine.api.users.User;
import com.music.client.member.MemberClient;
import com.music.common.logging.CommonLogger;
import com.music.service.members.beans.Member;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private MemberClient mMemberClient;
	private static final Logger log = CommonLogger.getLogger();

	public boolean preHandle(HttpServletRequest pRequest,
			HttpServletResponse pResponse, Object pCommand) throws Exception {
		log.debug("Inside login interceptor");
		System.out.println("Inside login interceptor");
		User user = (User) pRequest.getAttribute("user");
		System.out.println(user.getEmail());
		Member member = getMemberClient().getMember(user.getEmail(), true);
		member.setNickName(user.getNickname());
		pRequest.setAttribute("member", member);
		return true;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle
	 * (javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, java.lang.Object,
	 * org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest pRequest,
			HttpServletResponse pResponse, Object pHandler,
			ModelAndView pModelAndView) throws Exception {
		// Populate environment urls.
		Member member = (Member)pRequest.getAttribute("member");
		pModelAndView.addObject("member",member);
	}

	/**
	 * @return the memberClient
	 */
	public MemberClient getMemberClient() {
		return mMemberClient;
	}

	/**
	 * @param pMemberClient
	 *            the memberClient to set
	 */
	@Required
	public void setMemberClient(MemberClient pMemberClient) {
		mMemberClient = pMemberClient;
	}

}